﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Database.Entity;
using ASBCC.Database.Service;
using System.Data;
using ASBCC.Workflow.K2Manager;
using ASBCC.Business;
using Telerik.Web.UI;
using BEGDC.CC.Web.Common;
using BEGDC.Utility.Extensions;


namespace BEGDC.CC.Web.Workflow.Admin
{
    public partial class FlowProcessActivityGoto : System.Web.UI.Page
    {
        #region Define
        private ProcessBusiness processBusiness = new ProcessBusiness();
        #endregion

        #region PageLoad
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //txtTargetEn.Attributes["readonly"] = "readonly";
                BindProcNameDropdownlist();
                BindNextActivity();
                //ucPager.Query();
            }
        }
        #endregion

        #region Event


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ucPager.Query();
        }

        protected void btnGoto_Click(object sender, EventArgs e)
        {
            int userId;

            //wsq： 这里的 SearchStaff.EmployeeID 的值取的是数据库字段 EmployeeNo（值 CV0102267），
            //      往K2AuditDestination里存的需要是数据库字段 EmployeeID（值 123456）

            //string val1 = EmployeeManager.GetValue("EmployeeID", string.Format("EmployeeNo = '{0}'", SearchStaff.EmployeeID));
            //bool userIdRes = int.TryParse(val1, out userId); //int.TryParse(hidTargetUserId.Value, out userId);
            //if (!userIdRes || RadGrid1.SelectedIndexes.Count <= 0) return;

            EmployeeTableEntity ent1 = EmployeeManager.SelectByKeys(SearchStaff.EmployeeID);
            if (ent1 == null || ent1.EmployeeID == null || RadGrid1.SelectedIndexes.Count <= 0) return;
            userId = int.Parse(ent1.EmployeeID.ToString());

            string strMyActivityID = RadGrid1.SelectedValue.ToString();
            string nextActivity = ddlNextActivity.SelectedValue;
            Guid myActivityId = new Guid(strMyActivityID);
            MyActivityTableEntity myActivity = MyActivityManager.SelectByKeys(myActivityId);


            K2Console console = new K2Console();

            console.WorkItem.ActInstDestId = myActivity.K2ActInstDestID ?? 0;
            console.WorkItem.ActionRecordId = myActivity.ActionRecordID ?? Guid.Empty;
            console.WorkItem.ActivityName = myActivity.K2ActivityName;
            console.WorkItem.ArrvialDate = myActivity.ArrvialDate ?? DateTime.Now;
            console.WorkItem.Destination = myActivity.K2Destination;
            console.WorkItem.MyActivityId = myActivity.MyActivityID ?? Guid.Empty;
            console.WorkItem.ProcInstId = myActivity.K2ProcInstID ?? 0;
            console.WorkItem.ProcName = myActivity.ProcName;

            console.AppForm.Folio = myActivity.K2Folio;
            console.AppForm.Applicant.UserId = myActivity.ApplicantID ?? 0;
            console.AppForm.Applicant.UserEn = myActivity.ApplicantEn;
            console.AppForm.Applicant.UserCn = myActivity.ApplicantCn;
            console.AppForm.Creator.UserId = myActivity.CreatorID ?? 0;
            console.AppForm.Creator.UserEn = myActivity.CreatorEn;
            console.AppForm.Creator.UserCn = myActivity.CreatorCn;
            console.AppForm.ApplicationNo = myActivity.ApplicationNo;
            console.AppForm.DelegateFrom.UserId = myActivity.DelegateFromID ?? 0;
            console.AppForm.DelegateFrom.UserEn = myActivity.DelegateFromEn;
            console.AppForm.DelegateFrom.UserCn = myActivity.DelegateFromCn;
            console.AppForm.FormId = myActivity.FormID ?? 0;
            console.AppForm.Title = myActivity.Title;

            console.AuditDestination = new K2AuditDestination(nextActivity, new int[] { userId });
            console.ActionInfo.ActionType = K2ActionType.Goto;
            console.DataFields.Add(K2Consts.DataField_Key_FormURL, myActivity.FormURL);
            console.Execute();
            ucPager.Refresh();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            Guid id = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["MyActivityID"].ToString());
            List<Guid> list = new List<Guid>();
            list.Add(id);
            processBusiness.MoveMyActivity(list);
            ucPager.Refresh();
        }

        #endregion

        #region Function

        protected void ucPager_OnNeedDataSource(object sender, PagerEventArgs e)
        {
            string ownerEn = txtOwner.Text.Trim().SanitizeSqlValue();
            string procName = ddlProcName.SelectedValue;
            string applicationNo = txtApplicationNo.Text.Trim().SanitizeSqlValue();
            int formId = -1;
            //bool resFormId = int.TryParse(txtFormId.Text, out formId);
            //if (!resFormId) formId = -1;

            object count = 0;
            ucPager.DataSource = DatabaseManager.usp3_Select_MyActivity(applicationNo, formId, e.IsLast, "", ownerEn, ucPager.PageIndex, ucPager.PageSize, procName, ref count);
            ucPager.RowsCount = (int)count;

            trAction.Style["display"] = ((int)count > 0) ? "" : "none";
        }

        private void BindProcNameDropdownlist()
        {
            Flow_ProcessTableEntitySet set = Flow_ProcessManager.SelectAll();
            DataTable dt = null;
            if (set != null && set.Tables.Count > 0)
            {
                dt = set.Tables[0];
            }

            DataView dv = new DataView(dt);
            dv.Sort = "ProcName";

            ddlProcName.DataTextField = "ProcDisplayEn";
            ddlProcName.DataValueField = "ProcName";
            ddlProcName.DataSource = dv;
            ddlProcName.DataBind();
        }

        private void BindNextActivity()
        {
            string procName = ddlProcName.SelectedValue;
            Flow_ProcessConfigTableEntitySet set = Flow_ProcessConfigManager.SelectByCondition(string.Format("ProcName='{0}'", procName));
            DataTable dtProcessConfig = null;
            if (set != null && set.Tables.Count > 0)
            {
                dtProcessConfig = set.Tables[0];
            }
            DataView dv = new DataView(dtProcessConfig);
            dv.Sort = "OrderIndex";
            ddlNextActivity.DataSource = dv;
            ddlNextActivity.DataTextField = "ActivityName";
            ddlNextActivity.DataValueField = "ActivityName";
            ddlNextActivity.DataBind();
        }
        #endregion
        protected void ddlProcName_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindNextActivity();
            ucPager.Query();
        }

        //public string LastLoginTime
        //{
        //    get
        //    {
        //        if (Page.Request.Cookies["LastLoginTime"] == null)
        //            return string.Empty;
        //        else
        //            return Page.Request.Cookies["LastLoginTime"].Value.ToString();
        //    }

        //}

        
    }
}
